package com.ruoyi.framework.manager;

import java.util.TimerTask;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import com.ruoyi.common.utils.Threads;
import com.ruoyi.common.utils.spring.SpringUtils;
import org.apache.commons.lang3.concurrent.BasicThreadFactory;

/**
 * 异步任务管理器
 * 
 * @author ruoyi
 */
public class AsyncManager
{
    /**
     * 操作延迟10毫秒
     */
    private final int OPERATE_DELAY_TIME = 10;

    /**
     * 异步操作任务调度线程池（延迟获取，避免在销毁阶段初始化失败）
     */
    private volatile ScheduledExecutorService executor;

    private ScheduledExecutorService getExecutor()
    {
        if (executor == null)
        {
            synchronized (this)
            {
                if (executor == null)
                {
                    try
                    {
                        executor = SpringUtils.getBean("scheduledExecutorService");
                    }
                    catch (Exception e)
                    {
                        // 在销毁阶段或容器未就绪时，使用本地兜底线程池，避免类初始化失败
                        executor = new ScheduledThreadPoolExecutor(1,
                                new BasicThreadFactory.Builder().namingPattern("async-fallback-%d").daemon(true).build(),
                                new ThreadPoolExecutor.CallerRunsPolicy())
                        {
                            @Override
                            protected void afterExecute(Runnable r, Throwable t)
                            {
                                super.afterExecute(r, t);
                                Threads.printException(r, t);
                            }
                        };
                    }
                }
            }
        }
        return executor;
    }

    /**
     * 单例模式
     */
    private AsyncManager(){}

    private static AsyncManager me = new AsyncManager();

    public static AsyncManager me()
    {
        return me;
    }

    /**
     * 执行任务
     * 
     * @param task 任务
     */
    public void execute(TimerTask task)
    {
        getExecutor().schedule(task, OPERATE_DELAY_TIME, TimeUnit.MILLISECONDS);
    }

    /**
     * 停止任务线程池
     */
    public void shutdown()
    {
        ScheduledExecutorService ex = executor;
        if (ex != null)
        {
            Threads.shutdownAndAwaitTermination(ex);
        }
    }
}
